package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.dto.UserLoginDTO;
import com.itheima.properties.WeChatProperties;
import com.itheima.ship.po.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.utils.HttpClientUtil;
import com.itheima.vo.ShipVO;
import com.itheima.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.net.http.HttpClient;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * <p>
 * 微信用户 服务实现类
 * </p>
 *
 * @author 郑哥
 * @since 2024-05-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    public static final String WX_LOGIN  = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) throws LoginException {
        String openid = getOpenId(userLoginDTO.getCode());
        if(openid == null){
            throw  new LoginException("登录失败");
        }
       User user  = userMapper.getByOpenId(openid);
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);

        }
        return user;
    }

    public String getOpenId(String code){
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;

    }

    @Override
    public ShipVO getData(Long id) {
         ShipVO shipVO = userMapper.getData(id);
         return shipVO;
    }
}
